//
//  HotSearchView.m
//  Mango
//
//  Created by lanou3g on 16/5/13.
//  Copyright © 2016年 lanou3g. All rights reserved.
//

#import "HotSearchView.h"
#define KColor arc4random()% 256 / 255.0
@interface HotSearchView ()
@property (nonatomic, strong) UILabel *label;
@property (nonatomic, assign) CGFloat buttonX;

@end

@implementation HotSearchView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        UILabel *label = [[UILabel alloc]init];
        label.text = @"热门搜索";
        [self addSubview:label];
        self.label = label;
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.label.frame = CGRectMake(10, 10, 80, 40);
}

- (void)setTitles:(NSMutableArray *)titles {
    if (_titles != titles) {
        _titles = titles;
        CGFloat btnH = 30;
        self.buttonX = 10;
        CGFloat btnY = 60;
        for (int i = 0; i < self.titles.count; i++) {
            CGFloat btnW = [self titleWidthString:titles[i]];
           if (self.buttonX + btnW > ScreenSizeW - 8) {
                btnY = 100;
                self.buttonX = 10;
            }
            UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
            button.frame = CGRectMake(self.buttonX, btnY, btnW, btnH);
            self.buttonX += btnW + 10;
            
            [button setTitle:self.titles[i] forState:(UIControlStateNormal)];
            [button setBackgroundColor:[UIColor colorWithRed:KColor green:KColor blue:KColor alpha:1]];
            [button addTarget:self action:@selector(didClickButton:) forControlEvents:(UIControlEventTouchUpInside)];
            
            button.layer.cornerRadius = 10;
            button.layer.masksToBounds = YES;
            [self addSubview:button];
        }
    }
}

- (void)didClickButton:(UIButton *)button {
    if ([self.delegate respondsToSelector:@selector(hotsSearchViewdidClickButton:)]) {
        [self.delegate hotsSearchViewdidClickButton:button.currentTitle];
    }
}

- (CGFloat)titleWidthString:(NSString *)text {
    NSDictionary *dict = @{NSFontAttributeName : [UIFont systemFontOfSize:25]};
    CGSize size = CGSizeMake(MAXFLOAT, 30);
    CGFloat width = [text boundingRectWithSize:size options:(NSStringDrawingUsesLineFragmentOrigin) attributes:dict context:nil].size.width;
    return width;
}

#pragma mark 切换至夜间模式
- (void)updateToNightSkinMode {
    self.backgroundColor = [UIColor blackColor];
    self.label.textColor = [UIColor grayColor];
//    for (UIView *subView in self.subviews) {
//        if ([subView isKindOfClass:[UIButton class]]) {
//             [(UIButton *)subView setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
//        }
//    }
}

- (void)updateToDaySkinMode {
    self.backgroundColor = [UIColor whiteColor];
    self.label.textColor = [UIColor blackColor];
}


@end
